<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>地址查询</title>
</head>
<body>
	<div>
		请输入地址名称:&nbsp;&nbsp;<input type="text" id="addr" size="30"/>
		<div id="content"></div>
	</div>
	<script type="text/javascript">
		(function(){
			var addr = document.getElementById("addr");
			var top = getTop(addr)-10;
			var left = getLeft(addr)-8;
			var width = getWith(addr);
			var height = getHeight(addr);
			var div = document.getElementById("content");
			
			//失去焦点
			addr.addEventListener("blur",function(){
				// div.innerHTML="";
			});
			//按键事件
			addr.addEventListener("keyup",function(){
				var value = addr.value;
				if(!value){
					div.innerHTML="";
					return;
				}
				var search = searchAddr("addrSearch?cityName="+value,"GET",div);
				search.sendGet();
			});

			//获取控件的偏移位置
			function getTop(e) {  
			    var t=e.offsetTop;   
			    while(e=e.offsetParent) {  
			         t+=e.offsetTop;   
			     } 
			     return t; 
			}
			function getLeft(e){
				var l = e.offsetLeft;
				while(e=e.offsetParent){
					l+=e.offsetLeft;
				}
				return l;
			}
			function getWith(e){
				var w = e.offsetWidth;
				return w;
			}
			function getHeight(e){
				var h = e.offsetHeight;
				return h;
			}

			//查询地址，使用闭包
			function searchAddr(url,method,divEle){
				var obj={}
				obj.sendGet=function(){	//发送ajax请求
					var xhr = new XMLHttpRequest();
					xhr.open(method,url);
					xhr.onreadystatechange=function(){
						if(xhr.status==200 && xhr.readyState==4){
							console.log(xhr.responseText);
							obj.parseResponse(xhr.responseText);	//解析回调数据
						}
					}
					if(method=='GET'){
						xhr.send(null);
					}
				}
				obj.parseResponse=function(resp){	//模型数据渲染
					console.log(resp);
					divEle.innerHTML="";
					var addrs = JSON.parse(resp);
					if(!addrs.length){
						return;
					}
					var table=document.createElement("table");
					table.setAttribute("width",width);
					table.setAttribute("style","margin-left:"+left+"px;margin-top:"+top+"px;border:1px solid blue;");
					addrs.forEach((item,index)=>{
						var tr = document.createElement("tr");
						var td = document.createElement("td");
						td.innerHTML=item.area;
						tr.appendChild(td);
						table.appendChild(tr);
					});
					divEle.appendChild(table);
				}
				return obj;
			}
		})();
	</script>
</body>
</html>